/*-----------------------------------------------------------------------*/
/* Low level disk I/O module skeleton for Petit FatFs (C)ChaN, 2014      */
/*-----------------------------------------------------------------------*/

#include "diskio.h"

#include "sdcard_spi.h"

extern SDC_SpiHwDrv_T sdcard_spi_hw_driver;
SDC_Info_T sdcard_info;

uint8_t sdcard_read_buff_block[SDC_BLOCK_SIZE_BYTE];
uint8_t sdcard_write_buff_block[SDC_BLOCK_SIZE_BYTE];
volatile uint32_t sdcard_last_read_block_index = (uint32_t)(-1);

/*-----------------------------------------------------------------------*/
/* Initialize Disk Drive                                                 */
/*-----------------------------------------------------------------------*/

DSTATUS disk_initialize (void)
{
	DSTATUS stat = RES_OK;

	// Put your code here
    /* sdcard init. */
    bool err = false;
    SDC_Install(&sdcard_spi_hw_driver);
    do
    {
        err = SDC_InitCard(&sdcard_info);
    } while (err == false);

    if (err == false)
    {
        stat = RES_NOTRDY; /* disk is not ready. */
    }

	return stat;
}



/*-----------------------------------------------------------------------*/
/* Read Partial Sector                                                   */
/*-----------------------------------------------------------------------*/

DRESULT disk_readp (
	BYTE* buff,		/* Pointer to the destination object */
	DWORD sector,	/* Sector number (LBA) */
	UINT offset,	/* Offset in the sector */
	UINT count		/* Byte count (bit15:destination) */
)
{
	DRESULT res = RES_OK;

	// Put your code here
    if (sdcard_last_read_block_index != sector)
    {
        SDC_ReadBlock(sector, sdcard_read_buff_block);
        sdcard_last_read_block_index = sector;
    }

    for (uint32_t i = 0u; i < count; i++)
    {
        *buff++ = sdcard_read_buff_block[offset + i];
    }

	return res;
}



/*-----------------------------------------------------------------------*/
/* Write Partial Sector                                                  */
/*-----------------------------------------------------------------------*/

DRESULT disk_writep (
	BYTE* buff,		/* Pointer to the data to be written, NULL:Initiate/Finalize write operation */
	DWORD sc		/* Sector number (LBA) or Number of bytes to send */
)
{
	DRESULT res = RES_OK;


	if (!buff) {
		if (sc) {

			// Initiate write process

		} else {

			// Finalize write process

		}
	} else {

		// Send data to the disk

	}

	return res;
}

